﻿using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace BToolkit
{
    public class TouchMoveUIByOneFinger : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
    {
        public bool testInEditor;

        RectTransform trans;
        Vector2 previousPos;
        Vector2 canvasResolution;
        int fingerId = -1;

        void Awake()
        {
            trans = transform as RectTransform;
            CanvasScaler canvasScaler = FindObjectOfType<CanvasScaler>();
            if (canvasScaler.matchWidthOrHeight > 0.5f)
            {
                canvasResolution = new Vector2(canvasScaler.referenceResolution.y * (float)Screen.width / (float)Screen.height, canvasScaler.referenceResolution.y);
            }
            else
            {
                canvasResolution = new Vector2(canvasScaler.referenceResolution.x, canvasScaler.referenceResolution.x * (float)Screen.height / (float)Screen.width);
            }
        }

        void Update()
        {
            if (testInEditor && Application.isEditor)
            {
                if (Input.GetMouseButtonDown(0))
                {
                    OnDown(Input.mousePosition);
                }
                if (Input.GetMouseButton(0))
                {
                    OnDrag(Input.mousePosition);
                }
            }
            else
            {
                if (fingerId >= 0 && Input.touchCount > 0)
                {
                    for (int i = 0; i < Input.touchCount; i++)
                    {
                        Touch touch = Input.GetTouch(i);
                        if (touch.fingerId == fingerId && touch.phase == TouchPhase.Moved)
                        {
                            OnDrag(touch.position);
                        }
                    }
                }
            }
        }

        public virtual void OnPointerDown(PointerEventData eventData)
        {
            OnDown(eventData.position);
            fingerId = eventData.pointerId;
        }

        public virtual void OnPointerUp(PointerEventData eventData)
        {
            if(fingerId == eventData.pointerId)
            {
                fingerId = -1;
            }
        }

        void OnDown(Vector2 screenPos)
        {
            previousPos = ToUGUIPos(screenPos);
        }

        void OnDrag(Vector2 screenPos)
        {
            Vector2 pos = ToUGUIPos(screenPos);
            Vector2 deltaPos = pos - previousPos;
            previousPos = pos;
            trans.anchoredPosition += deltaPos;
        }

        Vector2 ToUGUIPos(Vector2 screenPos)
        {
            float x = canvasResolution.x * screenPos.x / (float)Screen.width - canvasResolution.x * 0.5f;
            float y = canvasResolution.y * screenPos.y / (float)Screen.height - canvasResolution.y * 0.5f;
            return new Vector2(x, y);
        }
    }
}